﻿using AutoMapper;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 居住-场所商业数据信息服务
    /// </summary>
    public class PlaceResidentController : BaseController<PlaceResidentController>
    {
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly IStorageProvider _storageProvider;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmBuildings> _buildingsRepository;
        private readonly IRepository<ZmBuildingsLayer> _buildingsLayerRepository;
        private readonly IRepository<ZmPlaceResident> _placeResidentRepository;
        private readonly IRepository<ZmPlaceResidentCheck> _placeResidentCheckRepository;
        private readonly IRepository<ZmPlaceCommercial> _placeCommercialRepository;
        
        private readonly Microsoft.AspNetCore.Http.Features.FormOptions _defaultFormOptions = new Microsoft.AspNetCore.Http.Features.FormOptions();
        private readonly string[] _permittedExtensions = { ".mp3", ".mp4", ".jpg", ".jpeg", ".png", ".geojson", ".doc", ".docx" };

        public PlaceResidentController(IStorageProvider storageProvider
            , IRepository<ZmUser> userRepository
            , IRepository<ZmBuildings> buildingsRepository
            , IRepository<ZmBuildingsLayer> buildingsLayerRepository
            , IRepository<ZmPlaceResident> placeResidentRepository
            , IRepository<ZmPlaceResidentCheck> placeResidentCheckRepository
             , IRepository<ZmPlaceCommercial> placeCommercialRepository
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , ILogger<PlaceResidentController> logger
            , IRepository<ZmSystemLog> systemLogRepository) : base(logger, systemLogRepository)
        {
            _storageProvider = storageProvider;
            _mapper = mapper;
            _dbContext = dbContext;
            _cache = cacheProvider.CreateCache();

            _userRepository = userRepository;
            _buildingsRepository = buildingsRepository;
            _buildingsLayerRepository = buildingsLayerRepository;
            _placeResidentRepository = placeResidentRepository;
            _placeCommercialRepository = placeCommercialRepository;
            _placeResidentCheckRepository = placeResidentCheckRepository;
        }

        /// <summary>
        /// 提交场所排查完成
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/place-resident/{pid}/submit")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet PlaceResidentSubmit([FromRoute] string id, [FromRoute] string pid)
        {
            if (!ModelState.IsValid)
            {
                return new RespRet(false, "Invalid Request");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid && _.IsDelete != 1);
            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            if (data.Type == 0) // 消防
            {
                data.Pczt = data.NumyhwtXf != null && data.NumyhwtXf > 0 ? 21 : 20;
             
            }
            else
            {
                data.Pczt = data.NumyhwtGa != null && data.NumyhwtGa > 0 ? 21 : 20;
            }



       
            _placeResidentRepository.Update(data);
            _placeResidentRepository.SaveChanges();



            //修改房屋状态
            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<string>(false, "用户名不存在");
            }
            var userDto = _mapper.Map<UserDto>(user);
            var house = _buildingsLayerRepository.FirstOrDefault(_ => _.Id == data.HouseId && _.IsDelete != 1);
            int count1 = 0;
            int count2 = 0;
            if (userDto.UserGroup == UserGroupType.FireControl)
            {
                count1 = _placeResidentRepository.Count(_ => _.HouseId == id
           && _.IsDelete != 1 && (((_.NumyhwtXf != null && _.NumyhwtXf > 0))));
                count2 = _placeCommercialRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtXf != null && _.NumyhwtXf > 0))));

            }
            else if (userDto.UserGroup == UserGroupType.Police)
            {
                count1 = _placeResidentRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtGa != null && _.NumyhwtGa > 0))));
                count2 = _placeCommercialRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtGa != null && _.NumyhwtGa > 0))));
            }

            //把这个房屋下面的，全部场所（居住和商业）。过滤(消防 type=0) 排查中 pczt>0同时，隐患项不等于空的场所，提交。
            //找出所有场所
            var csjz = _placeResidentRepository.Query(c => c.HouseId == id && c.IsDelete != 1 && c.Type == 0 && c.Pczt > 0 && (c.NumyhwtXf != null && c.AboveThreeFloorSelf != null)).ToList();
            var cssy = _placeCommercialRepository.Query(c => c.HouseId == id && c.IsDelete != 1 && c.Type == 0 && c.Pczt > 0 && (c.NumyhwtXf != null && c.AboveThreeFloorSelf != null)).ToList();
            //居住
            foreach (var item in csjz)
            {
                if (item.NumyhwtXf == 0)
                {
                    item.Pczt = 20;
                    _placeResidentRepository.Update(item);
                    _placeResidentRepository.SaveChanges();
                }
                else if (item.NumyhwtXf > 0)
                {
                    item.Pczt = 21;
                    _placeResidentRepository.Update(item);
                    _placeResidentRepository.SaveChanges();
                }
            }
            //商业
            foreach (var item in cssy)
            {
                if (item.NumyhwtXf == 0)
                {
                    item.Pczt = 20;
                    _placeCommercialRepository.Update(item);
                    _placeCommercialRepository.SaveChanges();
                }
                else if (item.NumyhwtXf > 0)
                {
                    item.Pczt = 21;
                    _placeCommercialRepository.Update(item);
                    _placeCommercialRepository.SaveChanges();
                }
            }


            if (count1 + count2 > 0)
            {
                if (userDto.UserGroup == UserGroupType.Housing)
                {
                    house.PcztHousing = 21;
                }
                else if (userDto.UserGroup == UserGroupType.FireControl)
                {
                    house.PcztFire = 21;
                }
                else if (userDto.UserGroup == UserGroupType.Police)
                {
                    house.PcztPolice = 21;
                }
            }
            else
            {
                if (userDto.UserGroup == UserGroupType.Housing)
                {
                    house.PcztHousing = 20;
                }
                else if (userDto.UserGroup == UserGroupType.FireControl)
                {
                    house.PcztFire = 20;
                }
                else if (userDto.UserGroup == UserGroupType.Police)
                {
                    house.PcztPolice = 20;
                }
            }
            house.ModifiedOn = DateTime.Now;
            _buildingsLayerRepository.Update(house);
            _buildingsLayerRepository.SaveChanges();

            return new RespRet(true, "Ok");
        }

        #region 消防安全

        /// <summary>
        /// 获取消防安全场所排查记录列表
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/{id}/fire-safety/place-resident/list")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<PlaceResidentFireDto>>), 200)]
        public RespRet<Page<PlaceResidentFireDto>> FireSafetyPlaceList([FromRoute] string id,
            [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<PlaceResidentFireDto>>(false, "PageIndex must >= 0");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<PlaceResidentFireDto>>(false, "user not logined");
            }

            Page<PlaceResidentFireDto> datas = null;
            if (!string.IsNullOrEmpty(pageRequest.Text))
            {
                if (pageRequest.Pczt.HasValue)
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 0
                             where place.PlaceName != null
                             where place.PlaceName.Contains(pageRequest.Text)
                             where place.Pczt == pageRequest.Pczt.Value
                             select _mapper.Map<PlaceResidentFireDto>(place))
                    .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 0
                             where place.PlaceName != null
                             where place.PlaceName.Contains(pageRequest.Text)
                             select _mapper.Map<PlaceResidentFireDto>(place))
                    .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
            }
            else
            {
                if (pageRequest.Pczt.HasValue)
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 0
                             where place.Pczt == pageRequest.Pczt.Value
                             select _mapper.Map<PlaceResidentFireDto>(place))
                    .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 0
                             select _mapper.Map<PlaceResidentFireDto>(place))
                    .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
            }

            return new RespRet<Page<PlaceResidentFireDto>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取消防安全场所排查信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid">场所ID</param>
        /// <returns></returns>
        [HttpGet("houses/{id}/fire-safety/place-resident/{pid}/info")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<PlaceResidentFireDto>), 200)]
        public RespRet<PlaceResidentFireDto> GetFireSafetyPlaceById([FromRoute] string id, [FromRoute] string pid)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PlaceResidentFireDto>(false, "user not logined");
            }

            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid && _.IsDelete != 1);
            if (null == data)
            {
                return new RespRet<PlaceResidentFireDto>(false, "不存在");
            }

            return new RespRet<PlaceResidentFireDto>(true, "Ok", _mapper.Map<PlaceResidentFireDto>(data));
        }

        /// <summary>
        /// 编辑消防安全场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/fire-safety/place-resident/{pid}/edit")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet EditFireSafetyPlace([FromRoute] string id, [FromRoute] string pid
            , [FromBody] PlaceResidentFireInput request)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            if (request.IsCheckWork)
            {
                if (string.IsNullOrEmpty(request.CheckMind))
                {
                    return new RespRet(false, "整治核查必须填写核查意见");
                }
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<string>(false, "用户名不存在");
            }

            var userDto = _mapper.Map<UserDto>(user);

            var house = _buildingsLayerRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            if (null == house)
            {
                return new RespRet<string>(false, "房屋不存在");
            }



            //修改历史创建时间
            DateTime setcdate = Convert.ToDateTime("2023-03-16 00:00:01.978547");
            var data1 = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid && _.IsDelete != 1 && _.CreateOn <= setcdate && _.Type == 0);
            var datacheck = _placeResidentCheckRepository.FirstOrDefault(_ => _.PlaceId == pid && _.IsDelete != 1 && _.Type == 0);

            if (null == datacheck && data1 != null)
            {
                data1.CreateOn = DateTime.Now;
                _placeResidentRepository.Update(data1);
                _placeResidentRepository.SaveChanges();
            }



            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid
             && _.IsDelete != 1 && _.Type == 0);
            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            if (userDto.UserGroup == UserGroupType.Housing)
            {
                house.PcztHousing = 1;
            }
            else if (userDto.UserGroup == UserGroupType.FireControl)
            {
                house.PcztFire = 1;
            }
            else if (userDto.UserGroup == UserGroupType.Police)
            {
                house.PcztPolice = 1;
            }

  


            if (21 == data.Pczt)
            {
                return new RespRet<string>(false, "已完成排查，有隐患的场所，请通过整治核查进行消隐！");
            }
            //if (20 == data.Pczt)
            //{
            //    return new RespRet<string>(false, "已完成排查，无隐患的场所，无需重新编辑！");
            //}
          

  
      
            data.DealState = 0;
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    _buildingsLayerRepository.Update(house);
                    _buildingsLayerRepository.SaveChanges();

                    var ipAddress = this.IpAddress();
                    var time = DateTime.Now;

                    if (request.IsCheckWork && string.IsNullOrEmpty(data.CheckMind))
                    {// 插入最后一次排查记录到历史记录表
                        var checkId = SequentialGuid.SequentialGuidGenerator.Instance.NewGuid().ToString("N");
                        var checkData = new ZmPlaceResidentCheck
                        {
                            Id = checkId,
                            PlaceId = data.Id,
                            HouseId = data.HouseId,
                            Type = data.Type,
                            Pczt = data.Pczt,
                            PlaceName = data.PlaceName,
                            Location = data.Location,
                            Householder = data.Householder,
                            Contact = data.Contact,
                            Level = data.Level,
                            NumyhwtXf = data.NumyhwtXf,
                            MaxPopulation = data.MaxPopulation,
                            BuildingFloors = data.BuildingFloors,
                            LeaseRooms = data.LeaseRooms,
                            LeaseRoomPeoples = data.LeaseRoomPeoples,
                            UseElectricBicycle = data.UseElectricBicycle,
                            UseBottledLiquefiedGas = data.UseBottledLiquefiedGas,
                            UseStackedItems = data.UseStackedItems,
                            UseBurglarMesh = data.UseBurglarMesh,
                            UseCeiling = data.UseCeiling,
                            IsCompletelyIsolated = data.IsCompletelyIsolated,
                            UseFlammableMaterials = data.UseFlammableMaterials,
                            UnauthorizedElectricalConnect = data.UnauthorizedElectricalConnect,
                            ChargingFacilitiesNoStandard = data.ChargingFacilitiesNoStandard,
                            NotEnoughExits = data.NotEnoughExits,
                            UseElectricBicyclePhoto = data.UseElectricBicyclePhoto,
                            UseBottledLiquefiedGasPhoto = data.UseBottledLiquefiedGasPhoto,
                            UseStackedItemsPhoto = data.UseStackedItemsPhoto,
                            UseBurglarMeshPhoto = data.UseBurglarMeshPhoto,
                            UseCeilingPhoto = data.UseCeilingPhoto,
                            IsCompletelyIsolatedPhoto = data.IsCompletelyIsolatedPhoto,
                            UseFlammableMaterialsPhoto = data.UseFlammableMaterialsPhoto,
                            UnauthorizedElectricalConnectPhoto = data.UnauthorizedElectricalConnectPhoto,
                            ChargingFacilitiesNoStandardPhoto = data.ChargingFacilitiesNoStandardPhoto,
                            NotEnoughExitsPhoto = data.NotEnoughExitsPhoto,
                            HouseholderSign = data.HouseholderSign,
                            FireInspectorSign = data.FireInspectorSign,
                            EscapeStairsNum = data.EscapeStairsNum,
                            FirstExitNum = data.FirstExitNum,
                            FirstFloorArea = data.FirstFloorArea,
                            SmokeAlarmNum = data.SmokeAlarmNum,
                            SimpleSprinklerSystemNum = data.SimpleSprinklerSystemNum,
                            UseFlammableInsulationMaterials = data.UseFlammableInsulationMaterials,
                            UseFlammableDangerousGoods = data.UseFlammableDangerousGoods,
                            AboveThreeFloorSelf = data.AboveThreeFloorSelf,
                            UseIndependentSmokeAlarm = data.UseIndependentSmokeAlarm,
                            AboveThreeFloorsEscape = data.AboveThreeFloorsEscape,
                            UseFlammableInsulationMaterialsPhoto = data.UseFlammableInsulationMaterialsPhoto,
                            UseFlammableDangerousGoodsPhoto = data.UseFlammableDangerousGoodsPhoto,
                            AboveThreeFloorSelfPhoto = data.AboveThreeFloorSelfPhoto,
                            UseIndependentSmokeAlarmPhoto = data.UseIndependentSmokeAlarmPhoto,
                            AboveThreeFloorsEscapePhoto = data.AboveThreeFloorsEscapePhoto,
                            CreateBy = userNumber,
                            CreateOn = time,
                            CreateIp = ipAddress,
                            ModifiedBy = userNumber,
                            ModifiedOn = time,
                            ModifiedIp = ipAddress
                        };

                        _placeResidentCheckRepository.Insert(checkData);
                        _placeResidentCheckRepository.SaveChanges();
                    }

                    var yinhuan = CalcYinHuanNum(request);

                    data.HouseId = id;
                    data.Type = 0;
                    data.Pczt = 1;
                    data.PlaceName = request.PlaceName;
                    data.Location = request.Location;
                    data.Householder = request.Householder;
                    data.Contact = request.Contact;
                    data.Level = yinhuan.Item2;
                    data.NumyhwtXf = yinhuan.Item1;
                    data.MaxPopulation = request.MaxPopulation;
                    data.BuildingFloors = request.BuildingFloors;
                    data.LeaseRooms = request.LeaseRooms;
                    data.LeaseRoomPeoples = request.LeaseRoomPeoples;
                    data.UseElectricBicycle = request.UseElectricBicycle ? 1 : 0;
                    data.UseBottledLiquefiedGas = request.UseBottledLiquefiedGas ? 1 : 0;
                    data.UseStackedItems = request.UseStackedItems ? 1 : 0;
                    data.UseBurglarMesh = request.UseBurglarMesh ? 1 : 0;
                    data.UseCeiling = request.UseCeiling ? 1 : 0;
                    data.IsCompletelyIsolated = request.IsCompletelyIsolated ? 1 : 0;
                    data.UseFlammableMaterials = request.UseFlammableMaterials ? 1 : 0;
                    data.UnauthorizedElectricalConnect = request.UnauthorizedElectricalConnect ? 1 : 0;
                    data.ChargingFacilitiesNoStandard = request.ChargingFacilitiesNoStandard ? 1 : 0;
                    data.NotEnoughExits = request.NotEnoughExits ? 1 : 0;
                    data.UseElectricBicyclePhoto = request.UseElectricBicyclePhotos != null
                    ? JsonConvert.SerializeObject(request.UseElectricBicyclePhotos) : null;
                    data.UseBottledLiquefiedGasPhoto = request.UseBottledLiquefiedGasPhotos != null
                    ? JsonConvert.SerializeObject(request.UseBottledLiquefiedGasPhotos) : null;
                    data.UseStackedItemsPhoto = request.UseStackedItemsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseStackedItemsPhotos) : null;
                    data.UseBurglarMeshPhoto = request.UseBurglarMeshPhotos != null
                    ? JsonConvert.SerializeObject(request.UseBurglarMeshPhotos) : null;
                    data.UseCeilingPhoto = request.UseCeilingPhotos != null
                    ? JsonConvert.SerializeObject(request.UseCeilingPhotos) : null;
                    data.IsCompletelyIsolatedPhoto = request.IsCompletelyIsolatedPhotos != null
                    ? JsonConvert.SerializeObject(request.IsCompletelyIsolatedPhotos) : null;
                    data.UseFlammableMaterialsPhoto = request.UseFlammableMaterialsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableMaterialsPhotos) : null;
                    data.UnauthorizedElectricalConnectPhoto = request.UnauthorizedElectricalConnectPhotos != null
                    ? JsonConvert.SerializeObject(request.UnauthorizedElectricalConnectPhotos) : null;
                    data.ChargingFacilitiesNoStandardPhoto = request.ChargingFacilitiesNoStandardPhotos != null
                   ? JsonConvert.SerializeObject(request.ChargingFacilitiesNoStandardPhotos) : null;
                    data.NotEnoughExitsPhoto = request.NotEnoughExitsPhotos != null
                    ? JsonConvert.SerializeObject(request.NotEnoughExitsPhotos) : null;
                    data.HouseholderSign = request.HouseholderSign;
                    data.FireInspectorSign = request.FireInspectorSign;
                    data.EscapeStairsNum = request.EscapeStairsNum;
                    data.FirstExitNum = request.FirstExitNum;
                    data.FirstFloorArea = request.FirstFloorArea;
                    data.SmokeAlarmNum = request.SmokeAlarmNum;
                    data.SimpleSprinklerSystemNum = request.SimpleSprinklerSystemNum;
                    data.UseFlammableInsulationMaterials = request.UseFlammableInsulationMaterials ? 1 : 0;
                    data.UseFlammableDangerousGoods = request.UseFlammableDangerousGoods ? 1 : 0;
                    data.AboveThreeFloorSelf = request.AboveThreeFloorSelf ? 1 : 0;
                    data.UseIndependentSmokeAlarm = request.UseIndependentSmokeAlarm ? 1 : 0;
                    data.AboveThreeFloorsEscape = request.AboveThreeFloorsEscape ? 1 : 0;
                    data.UseFlammableInsulationMaterialsPhoto = request.UseFlammableInsulationMaterialsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableInsulationMaterialsPhotos) : null;
                    data.UseFlammableDangerousGoodsPhoto = request.UseFlammableDangerousGoodsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableDangerousGoodsPhotos) : null;
                    data.AboveThreeFloorSelfPhoto = request.AboveThreeFloorSelfPhotos != null
                    ? JsonConvert.SerializeObject(request.AboveThreeFloorSelfPhotos) : null;
                    data.UseIndependentSmokeAlarmPhoto = request.UseIndependentSmokeAlarmPhotos != null
                    ? JsonConvert.SerializeObject(request.UseIndependentSmokeAlarmPhotos) : null;
                    data.AboveThreeFloorsEscapePhoto = request.AboveThreeFloorsEscapePhotos != null
                    ? JsonConvert.SerializeObject(request.AboveThreeFloorsEscapePhotos) : null;
                    data.CheckMind = request.CheckMind;
                    data.CheckPhoto = request.CheckPhotos != null
                    ? JsonConvert.SerializeObject(request.CheckPhotos) : null;
                    data.ModifiedBy = userNumber;
                    data.ModifiedOn = time;
                    data.ModifiedIp = ipAddress;
                    _placeResidentRepository.Update(data);
                    _placeResidentRepository.SaveChanges();

                    trans.Complete();

                   
                }
                catch (Exception e)
                {
                    try
                    {
                        Transaction.Current.Rollback();
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                    return new RespRet(false, "更新失败");
                }
            }
            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 删除消防安全场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/fire-safety/place-resident/{pid}/delete")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet DeleteFireSafetyPlace([FromRoute] string id, [FromRoute] string pid)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid
            && _.IsDelete != 1 && _.Type == 0);
            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            _placeResidentRepository.Delete(data);
            _placeResidentRepository.SaveChanges();

            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 清空消防安全场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/fire-safety/place-resident/clear")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet ClearFireSafetyPlace([FromRoute] string id)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var sbSql = new StringBuilder();
            sbSql.Append($"delete from zm_place_resident where type=@type and house_id=@id");
            var sqlParameters = new List<NpgsqlParameter>();
            int type = 0;
            sqlParameters.Add(new NpgsqlParameter($"type", type));
            sqlParameters.Add(new NpgsqlParameter($"id", id));

            _dbContext.Database.ExecuteSqlRaw(sbSql.ToString(), sqlParameters.ToArray());
            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 整治核查消防安全场所
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/fire-safety/place-resident/{pid}/check")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet CheckFireSafetyPlace([FromRoute] string id, [FromRoute] string pid
            , [FromBody] PlaceResidentFireInput request)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            if (string.IsNullOrEmpty(request.CheckMind))
            {
                return new RespRet(false, "整治核查必须填写核查意见");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<string>(false, "用户名不存在");
            }

            var userDto = _mapper.Map<UserDto>(user);

            var house = _buildingsLayerRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            if (null == house)
            {
                return new RespRet<string>(false, "房屋不存在");
            }

            //修改历史创建时间
            DateTime setcdate = Convert.ToDateTime("2023-03-16 00:00:01.978547");
            var data1 = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid && _.IsDelete != 1 && _.CreateOn <= setcdate && _.Type == 0);
            var datacheck = _placeResidentCheckRepository.FirstOrDefault(_ => _.PlaceId == pid && _.IsDelete != 1 && _.Type == 0);

            if (null == datacheck && data1 != null)
            {
                data1.CreateOn = DateTime.Now;
                _placeResidentRepository.Update(data1);
                _placeResidentRepository.SaveChanges();
            }


            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid
             && _.IsDelete != 1 && _.Type == 0);
          


            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            //if (20 == data.Pczt)
            //{
            //    return new RespRet<string>(false, "已完成排查，无隐患的场所，无需整治核查进行消隐！");
            //}


            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    var ipAddress = this.IpAddress();
                    var time = DateTime.Now;

                    
               
                    var yinhuan = CalcYinHuanNum(request);
                    if (data.NumyhwtXf < yinhuan.Item1)
                    {
                     //   return new RespRet<string>(false, "整治核查进行只能消隐，不能添加新隐患！");
                    }


                    if (string.IsNullOrEmpty(data.CheckMind))
                    {// 插入最后一次排查记录到历史记录表
                        var lastData = new ZmPlaceResidentCheck
                        {
                            Id = SequentialGuid.SequentialGuidGenerator.Instance.NewGuid().ToString("N"),
                            PlaceId = data.Id,
                            HouseId = data.HouseId,
                            Type = data.Type,
                            Pczt = data.Pczt,
                            PlaceName = data.PlaceName,
                            Location = data.Location,
                            Householder = data.Householder,
                            Contact = data.Contact,
                            Level = data.Level,
                            NumyhwtXf = data.NumyhwtXf,
                            MaxPopulation = data.MaxPopulation,
                            BuildingFloors = data.BuildingFloors,
                            LeaseRooms = data.LeaseRooms,
                            LeaseRoomPeoples = data.LeaseRoomPeoples,
                            UseElectricBicycle = data.UseElectricBicycle,
                            UseBottledLiquefiedGas = data.UseBottledLiquefiedGas,
                            UseStackedItems = data.UseStackedItems,
                            UseBurglarMesh = data.UseBurglarMesh,
                            UseCeiling = data.UseCeiling,
                            IsCompletelyIsolated = data.IsCompletelyIsolated,
                            UseFlammableMaterials = data.UseFlammableMaterials,
                            UnauthorizedElectricalConnect = data.UnauthorizedElectricalConnect,
                            ChargingFacilitiesNoStandard = data.ChargingFacilitiesNoStandard,
                            NotEnoughExits = data.NotEnoughExits,
                            UseElectricBicyclePhoto = data.UseElectricBicyclePhoto,
                            UseBottledLiquefiedGasPhoto = data.UseBottledLiquefiedGasPhoto,
                            UseStackedItemsPhoto = data.UseStackedItemsPhoto,
                            UseBurglarMeshPhoto = data.UseBurglarMeshPhoto,
                            UseCeilingPhoto = data.UseCeilingPhoto,
                            IsCompletelyIsolatedPhoto = data.IsCompletelyIsolatedPhoto,
                            UseFlammableMaterialsPhoto = data.UseFlammableMaterialsPhoto,
                            UnauthorizedElectricalConnectPhoto = data.UnauthorizedElectricalConnectPhoto,
                            ChargingFacilitiesNoStandardPhoto = data.ChargingFacilitiesNoStandardPhoto,
                            NotEnoughExitsPhoto = data.NotEnoughExitsPhoto,
                            HouseholderSign = data.HouseholderSign,
                            FireInspectorSign = data.FireInspectorSign,
                            EscapeStairsNum = data.EscapeStairsNum,
                            FirstExitNum = data.FirstExitNum,
                            FirstFloorArea = data.FirstFloorArea,
                            SmokeAlarmNum = data.SmokeAlarmNum,
                            SimpleSprinklerSystemNum = data.SimpleSprinklerSystemNum,
                            UseFlammableInsulationMaterials = data.UseFlammableInsulationMaterials,
                            UseFlammableDangerousGoods = data.UseFlammableDangerousGoods,
                            AboveThreeFloorSelf = data.AboveThreeFloorSelf,
                            UseIndependentSmokeAlarm = data.UseIndependentSmokeAlarm,
                            AboveThreeFloorsEscape = data.AboveThreeFloorsEscape,
                            UseFlammableInsulationMaterialsPhoto = data.UseFlammableInsulationMaterialsPhoto,
                            UseFlammableDangerousGoodsPhoto = data.UseFlammableDangerousGoodsPhoto,
                            AboveThreeFloorSelfPhoto = data.AboveThreeFloorSelfPhoto,
                            UseIndependentSmokeAlarmPhoto = data.UseIndependentSmokeAlarmPhoto,
                            AboveThreeFloorsEscapePhoto = data.AboveThreeFloorsEscapePhoto,
                            CreateBy = userNumber,
                            CreateOn = time,
                            CreateIp = ipAddress,
                            ModifiedBy = userNumber,
                            ModifiedOn = time,
                            ModifiedIp = ipAddress
                        };

                        _placeResidentCheckRepository.Insert(lastData);
                        _placeResidentCheckRepository.SaveChanges();
                    }

          


                    data.HouseId = id;
                    data.PlaceName = request.PlaceName;
                    data.Location = request.Location;
                    data.Householder = request.Householder;
                    data.Contact = request.Contact;
                    data.Level = yinhuan.Item2;
                    data.NumyhwtXf = yinhuan.Item1;
                    data.Pczt = data.NumyhwtXf != null && data.NumyhwtXf > 0 ? 21 : 20;
                    data.MaxPopulation = request.MaxPopulation;
                    data.BuildingFloors = request.BuildingFloors;
                    data.LeaseRooms = request.LeaseRooms;
                    data.LeaseRoomPeoples = request.LeaseRoomPeoples;
                    data.UseElectricBicycle = request.UseElectricBicycle ? 1 : 0;
                    data.UseBottledLiquefiedGas = request.UseBottledLiquefiedGas ? 1 : 0;
                    data.UseStackedItems = request.UseStackedItems ? 1 : 0;
                    data.UseBurglarMesh = request.UseBurglarMesh ? 1 : 0;
                    data.UseCeiling = request.UseCeiling ? 1 : 0;
                    data.IsCompletelyIsolated = request.IsCompletelyIsolated ? 1 : 0;
                    data.UseFlammableMaterials = request.UseFlammableMaterials ? 1 : 0;
                    data.UnauthorizedElectricalConnect = request.UnauthorizedElectricalConnect ? 1 : 0;
                    data.ChargingFacilitiesNoStandard = request.ChargingFacilitiesNoStandard ? 1 : 0;
                    data.NotEnoughExits = request.NotEnoughExits ? 1 : 0;
                    data.UseElectricBicyclePhoto = request.UseElectricBicyclePhotos != null
                    ? JsonConvert.SerializeObject(request.UseElectricBicyclePhotos) : null;
                    data.UseBottledLiquefiedGasPhoto = request.UseBottledLiquefiedGasPhotos != null
                    ? JsonConvert.SerializeObject(request.UseBottledLiquefiedGasPhotos) : null;
                    data.UseStackedItemsPhoto = request.UseStackedItemsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseStackedItemsPhotos) : null;
                    data.UseBurglarMeshPhoto = request.UseBurglarMeshPhotos != null
                    ? JsonConvert.SerializeObject(request.UseBurglarMeshPhotos) : null;
                    data.UseCeilingPhoto = request.UseCeilingPhotos != null
                    ? JsonConvert.SerializeObject(request.UseCeilingPhotos) : null;
                    data.IsCompletelyIsolatedPhoto = request.IsCompletelyIsolatedPhotos != null
                    ? JsonConvert.SerializeObject(request.IsCompletelyIsolatedPhotos) : null;
                    data.UseFlammableMaterialsPhoto = request.UseFlammableMaterialsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableMaterialsPhotos) : null;
                    data.UnauthorizedElectricalConnectPhoto = request.UnauthorizedElectricalConnectPhotos != null
                    ? JsonConvert.SerializeObject(request.UnauthorizedElectricalConnectPhotos) : null;
                    data.ChargingFacilitiesNoStandardPhoto = request.ChargingFacilitiesNoStandardPhotos != null
                   ? JsonConvert.SerializeObject(request.ChargingFacilitiesNoStandardPhotos) : null;
                    data.NotEnoughExitsPhoto = request.NotEnoughExitsPhotos != null
                    ? JsonConvert.SerializeObject(request.NotEnoughExitsPhotos) : null;
                    data.HouseholderSign = request.HouseholderSign;
                    data.FireInspectorSign = request.FireInspectorSign;
                    data.EscapeStairsNum = request.EscapeStairsNum;
                    data.FirstExitNum = request.FirstExitNum;
                    data.FirstFloorArea = request.FirstFloorArea;
                    data.SmokeAlarmNum = request.SmokeAlarmNum;
                    data.SimpleSprinklerSystemNum = request.SimpleSprinklerSystemNum;
                    data.UseFlammableInsulationMaterials = request.UseFlammableInsulationMaterials ? 1 : 0;
                    data.UseFlammableDangerousGoods = request.UseFlammableDangerousGoods ? 1 : 0;
                    data.AboveThreeFloorSelf = request.AboveThreeFloorSelf ? 1 : 0;
                    data.UseIndependentSmokeAlarm = request.UseIndependentSmokeAlarm ? 1 : 0;
                    data.AboveThreeFloorsEscape = request.AboveThreeFloorsEscape ? 1 : 0;
                    data.UseFlammableInsulationMaterialsPhoto = request.UseFlammableInsulationMaterialsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableInsulationMaterialsPhotos) : null;
                    data.UseFlammableDangerousGoodsPhoto = request.UseFlammableDangerousGoodsPhotos != null
                    ? JsonConvert.SerializeObject(request.UseFlammableDangerousGoodsPhotos) : null;
                    data.AboveThreeFloorSelfPhoto = request.AboveThreeFloorSelfPhotos != null
                    ? JsonConvert.SerializeObject(request.AboveThreeFloorSelfPhotos) : null;
                    data.UseIndependentSmokeAlarmPhoto = request.UseIndependentSmokeAlarmPhotos != null
                    ? JsonConvert.SerializeObject(request.UseIndependentSmokeAlarmPhotos) : null;
                    data.AboveThreeFloorsEscapePhoto = request.AboveThreeFloorsEscapePhotos != null
                    ? JsonConvert.SerializeObject(request.AboveThreeFloorsEscapePhotos) : null;
                    data.CheckMind = request.CheckMind;
                    data.CheckPhoto = request.CheckPhotos != null
                    ? JsonConvert.SerializeObject(request.CheckPhotos) : null;
                    data.ModifiedBy = userNumber;
                    data.ModifiedOn = time;
                    data.ModifiedIp = ipAddress;
                    data.ModifiedOn = DateTime.Now;
                    data.DealState = 0;
                    _placeResidentRepository.Update(data);
                    _placeResidentRepository.SaveChanges();

                    var checkId = SequentialGuid.SequentialGuidGenerator.Instance.NewGuid().ToString("N");
                    var checkData = new ZmPlaceResidentCheck
                    {
                        Id = checkId,
                        PlaceId = data.Id,
                        HouseId = data.HouseId,
                        Type = data.Type,
                        Pczt = data.Pczt,
                        PlaceName = data.PlaceName,
                        Location = data.Location,
                        Householder = data.Householder,
                        Contact = data.Contact,
                        Level = data.Level,
                        NumyhwtXf = data.NumyhwtXf,
                        MaxPopulation = data.MaxPopulation,
                        BuildingFloors = data.BuildingFloors,
                        LeaseRooms = data.LeaseRooms,
                        LeaseRoomPeoples = data.LeaseRoomPeoples,
                        UseElectricBicycle = data.UseElectricBicycle,
                        UseBottledLiquefiedGas = data.UseBottledLiquefiedGas,
                        UseStackedItems = data.UseStackedItems,
                        UseBurglarMesh = data.UseBurglarMesh,
                        UseCeiling = data.UseCeiling,
                        IsCompletelyIsolated = data.IsCompletelyIsolated,
                        UseFlammableMaterials = data.UseFlammableMaterials,
                        UnauthorizedElectricalConnect = data.UnauthorizedElectricalConnect,
                        ChargingFacilitiesNoStandard = data.ChargingFacilitiesNoStandard,
                        NotEnoughExits = data.NotEnoughExits,
                        UseElectricBicyclePhoto = data.UseElectricBicyclePhoto,
                        UseBottledLiquefiedGasPhoto = data.UseBottledLiquefiedGasPhoto,
                        UseStackedItemsPhoto = data.UseStackedItemsPhoto,
                        UseBurglarMeshPhoto = data.UseBurglarMeshPhoto,
                        UseCeilingPhoto = data.UseCeilingPhoto,
                        IsCompletelyIsolatedPhoto = data.IsCompletelyIsolatedPhoto,
                        UseFlammableMaterialsPhoto = data.UseFlammableMaterialsPhoto,
                        UnauthorizedElectricalConnectPhoto = data.UnauthorizedElectricalConnectPhoto,
                        ChargingFacilitiesNoStandardPhoto = data.ChargingFacilitiesNoStandardPhoto,
                        NotEnoughExitsPhoto = data.NotEnoughExitsPhoto,
                        HouseholderSign = data.HouseholderSign,
                        FireInspectorSign = data.FireInspectorSign,
                        EscapeStairsNum = data.EscapeStairsNum,
                        FirstExitNum = data.FirstExitNum,
                        FirstFloorArea = data.FirstFloorArea,
                        SmokeAlarmNum = data.SmokeAlarmNum,
                        SimpleSprinklerSystemNum = data.SimpleSprinklerSystemNum,
                        UseFlammableInsulationMaterials = data.UseFlammableInsulationMaterials,
                        UseFlammableDangerousGoods = data.UseFlammableDangerousGoods,
                        AboveThreeFloorSelf = data.AboveThreeFloorSelf,
                        UseIndependentSmokeAlarm = data.UseIndependentSmokeAlarm,
                        AboveThreeFloorsEscape = data.AboveThreeFloorsEscape,
                        UseFlammableInsulationMaterialsPhoto = data.UseFlammableInsulationMaterialsPhoto,
                        UseFlammableDangerousGoodsPhoto = data.UseFlammableDangerousGoodsPhoto,
                        AboveThreeFloorSelfPhoto = data.AboveThreeFloorSelfPhoto,
                        UseIndependentSmokeAlarmPhoto = data.UseIndependentSmokeAlarmPhoto,
                        AboveThreeFloorsEscapePhoto = data.AboveThreeFloorsEscapePhoto,
                        CheckMind = data.CheckMind,
                        CheckPhoto = data.CheckPhoto,
                        CreateBy = userNumber,
                        CreateOn = time,
                        CreateIp = ipAddress,
                        ModifiedBy = userNumber,
                        ModifiedOn = time,
                        DealState = 0,
                        ModifiedIp = ipAddress
                    };

                    _placeResidentCheckRepository.Insert(checkData);
                    _placeResidentCheckRepository.SaveChanges();
                    trans.Complete();
                }
                catch (Exception e)
                {
                    try
                    {
                        Transaction.Current.Rollback();
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                    return new RespRet<long>(false, "整治核查失败");
                }
            }


            //修改房屋状态
            int count1 = 0;
            int count2 = 0;
            if (userDto.UserGroup == UserGroupType.FireControl)
            {
                count1 = _placeResidentRepository.Count(_ => _.HouseId == id
           && _.IsDelete != 1 && (((_.NumyhwtXf != null && _.NumyhwtXf > 0))));
                count2 = _placeCommercialRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtXf != null && _.NumyhwtXf > 0))));

            }
            else if (userDto.UserGroup == UserGroupType.Police)
            {
                count1 = _placeResidentRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtGa != null && _.NumyhwtGa > 0))));
                count2 = _placeCommercialRepository.Count(_ => _.HouseId == id
            && _.IsDelete != 1 && (((_.NumyhwtGa != null && _.NumyhwtGa > 0))));
            }


            if (count1 + count2 > 0)
            {
                if (userDto.UserGroup == UserGroupType.Housing)
                {
                    house.PcztHousing = 21;
                }
                else if (userDto.UserGroup == UserGroupType.FireControl)
                {
                    house.PcztFire = 21;
                }
                else if (userDto.UserGroup == UserGroupType.Police)
                {
                    house.PcztPolice = 21;
                }
            }
            else
            {
                if (userDto.UserGroup == UserGroupType.Housing)
                {
                    house.PcztHousing = 20;
                }
                else if (userDto.UserGroup == UserGroupType.FireControl)
                {
                    house.PcztFire = 20;
                }
                else if (userDto.UserGroup == UserGroupType.Police)
                {
                    house.PcztPolice = 20;
                }
            }
            house.ModifiedOn = DateTime.Now;
            _buildingsLayerRepository.Update(house);
            _buildingsLayerRepository.SaveChanges();

            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 获取消防安全场所的整治核查历史记录列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet("houses/{id}/fire-safety/place-resident/{pid}/check-result/history-list")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<PlaceResidentFireCheckDto>>), 200)]
        public RespRet<List<PlaceResidentFireCheckDto>> GetFireSafetyPlaceRstCheckListById(
            [FromRoute] string id, [FromRoute] string pid)
        {
            if (!ModelState.IsValid)
            {
                return new RespRet<List<PlaceResidentFireCheckDto>>(false, "Invalid Request");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<List<PlaceResidentFireCheckDto>>(false, "user not logined");
            }

            var datas = (from c in _dbContext.ZmPlaceResidentCheck
                         where c.IsDelete != 1
                         where c.HouseId == id
                         where c.PlaceId == pid
                         orderby c.CreateOn descending
                         select _mapper.Map<PlaceResidentFireCheckDto>(c))?.ToList();
            return new RespRet<List<PlaceResidentFireCheckDto>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取消防安全场所的整治核查历史记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("houses/fire-safety/place-resident/check-result/history-list/{id}/info")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<PlaceResidentFireCheckDto>), 200)]
        public RespRet<PlaceResidentFireCheckDto> FireSafetyPlaceRstCheckHistoryInfo(
            [FromRoute] string id)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PlaceResidentFireCheckDto>(false, "user not logined");
            }

            var data = _placeResidentCheckRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            if (null == data)
            {
                return new RespRet<PlaceResidentFireCheckDto>(false, "不存在");
            }

            return new RespRet<PlaceResidentFireCheckDto>(true, "Ok", _mapper.Map<PlaceResidentFireCheckDto>(data));
        }

        #endregion

        #region 综合

        /// <summary>
        /// 获取综合场所排查记录列表
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/{id}/integration/place-resident/list")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<PlaceResidentIntegrationDto>>), 200)]
        public RespRet<Page<PlaceResidentIntegrationDto>> IntegrationPlaceList([FromRoute] string id,
            [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<PlaceResidentIntegrationDto>>(false, "PageIndex must >= 0");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<PlaceResidentIntegrationDto>>(false, "user not logined");
            }

            //var house = _buildingsRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            //if (null == house)
            //{
            //    return new RespRet<Page<PlaceResidentIntegrationDto>>(false, "房屋不存在");
            //}

            Page<PlaceResidentIntegrationDto> datas = null;
            if (!string.IsNullOrEmpty(pageRequest.Text))
            {
                if (pageRequest.Pczt.HasValue)
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 1
                             where place.PlaceName != null
                             where place.PlaceName.Contains(pageRequest.Text)
                             where place.Pczt == pageRequest.Pczt.Value
                             select _mapper.Map<PlaceResidentIntegrationDto>(place))
                .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 1
                             where place.PlaceName != null
                             where place.PlaceName.Contains(pageRequest.Text)
                             select _mapper.Map<PlaceResidentIntegrationDto>(place))
                .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
            }
            else
            {
                if (pageRequest.Pczt.HasValue)
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 1
                             where place.Pczt == pageRequest.Pczt.Value
                             select _mapper.Map<PlaceResidentIntegrationDto>(place))
                     .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
                else
                {
                    datas = (from place in _dbContext.ZmPlaceResident
                             where place.IsDelete != 1
                             where place.HouseId == id
                             where place.Type == 1
                             select _mapper.Map<PlaceResidentIntegrationDto>(place))
                     .ToPagedList(pageRequest.PageIndex + 1, pageRequest.Limit);
                }
            }

            if (datas.Items != null)
            {
                foreach (var item in datas.Items)
                {
                    //if (!item.ChongDianVillage.HasValue && house.Check107.HasValue)
                    //{
                    //    item.ChongDianVillage = house.Check107 == 1;
                    //}

                    //if (!item.Level.HasValue)
                    //{
                    //    item.Level = house.Level;
                    //}
                }
            }

            return new RespRet<Page<PlaceResidentIntegrationDto>>(true, "Ok", datas);
        }

        /// <summary>
        /// 获取综合场所排查信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid">场所ID</param>
        /// <returns></returns>
        [HttpGet("houses/{id}/integration/place-resident/{pid}/info")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<PlaceResidentIntegrationDto>), 200)]
        public RespRet<PlaceResidentIntegrationDto> GetIntegrationPlaceById([FromRoute] string id, [FromRoute] string pid)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<PlaceResidentIntegrationDto>(false, "user not logined");
            }

            //var house = _buildingsRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            //if (null == house)
            //{
            //    return new RespRet<PlaceResidentIntegrationDto>(false, "房屋不存在");
            //}

            //var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid && _.IsDelete != 1);
            //if (null == data)
            //{
            //    return new RespRet<PlaceResidentIntegrationDto>(false, "不存在");
            //}

            //var dataDto = _mapper.Map<PlaceResidentIntegrationDto>(data);

            //if (!dataDto.ChongDianVillage.HasValue && house.Check107.HasValue)
            //{
            //    dataDto.ChongDianVillage = house.Check107 == 1;
            //}

            //if (!dataDto.Level.HasValue)
            //{
            //    dataDto.Level = house.Level;
            //}

            return new RespRet<PlaceResidentIntegrationDto>(true, "Ok", null);
        }

        /// <summary>
        /// 编辑综合场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/integration/place-resident/{pid}/edit")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet EditIntegrationPlace([FromRoute] string id, [FromRoute] string pid
            , [FromBody] PlaceResidentIntegrationInput request)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<string>(false, "用户名不存在");
            }

            var userDto = _mapper.Map<UserDto>(user);

            var house = _buildingsLayerRepository.FirstOrDefault(_ => _.Id == id && _.IsDelete != 1);
            if (null == house)
            {
                return new RespRet<string>(false, "房屋不存在");
            }

            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid
            && _.IsDelete != 1 && _.Type == 1);
            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            if (userDto.UserGroup == UserGroupType.Housing)
            {
                house.PcztHousing = 1;
            }
            else if (userDto.UserGroup == UserGroupType.FireControl)
            {
                house.PcztFire = 1;
            }
            else if (userDto.UserGroup == UserGroupType.Police)
            {
                house.PcztPolice = 1;
            }

            _buildingsLayerRepository.Update(house);
            _buildingsLayerRepository.SaveChanges();

            var yinhuan = CalcYinHuanNum(request);

            var ipAddress = this.IpAddress();
            var time = DateTime.Now;
            data.HouseId = id;
            data.Type = 1;
            data.Pczt = 1;
            data.NumyhwtGa = yinhuan.Item1;
            data.YhlxGa = yinhuan.Item2;
            data.PlaceName = request.PlaceName;
            data.Location = request.Location;
            data.Householder = request.Householder;
            data.Contact = request.Contact;
            data.ChongDianVillage = request.ChongDianVillage ? 1 : 0;
            data.Level = request.Level;
            data.RealPopulation = request.RealPopulation;
            data.RealPopulationAbove3Floors = request.RealPopulationAbove3Floors;
            data.Security = request.Security;
            data.SecurityRemediation = request.SecurityRemediation;
            data.IllegalConstruction = request.IllegalConstruction;
            data.IllegalConstructionRemediation = request.IllegalConstructionRemediation;
            data.IntegrationInspectorSign = request.IntegrationInspectorSign;
            data.BuildingAddress = request.BuildingAddress;
            data.ActualPerson = request.ActualPerson;
            data.ActualPersonPhone = request.ActualPersonPhone;
            data.AboveThreeFloorMaxPopulation = request.AboveThreeFloorMaxPopulation;
            data.ModifiedBy = userNumber;
            data.ModifiedOn = time;
            data.ModifiedIp = ipAddress;
            _placeResidentRepository.Update(data);
            _placeResidentRepository.SaveChanges();

            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 删除综合场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/integration/place-resident/{pid}/delete")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet DeleteIntegrationPlace([FromRoute] string id, [FromRoute] string pid)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var data = _placeResidentRepository.FirstOrDefault(_ => _.Id == pid
            && _.IsDelete != 1 && _.Type == 1);
            if (null == data)
            {
                return new RespRet(false, "不存在");
            }

            _placeResidentRepository.Delete(data);
            _placeResidentRepository.SaveChanges();

            return new RespRet(true, "Ok");
        }

        /// <summary>
        /// 清空综合场所排查记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("houses/{id}/integration/place-resident/clear")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet), 200)]
        public RespRet ClearIntegrationyPlace([FromRoute] string id)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet(false, "user not logined");
            }

            var sbSql = new StringBuilder();
            sbSql.Append($"delete from zm_place_resident where type=@type and house_id=@id");
            var sqlParameters = new List<NpgsqlParameter>();
            int type = 1;
            sqlParameters.Add(new NpgsqlParameter($"type", type));
            sqlParameters.Add(new NpgsqlParameter($"id", id));

            _dbContext.Database.ExecuteSqlRaw(sbSql.ToString(), sqlParameters.ToArray());
            return new RespRet(true, "Ok");
        }

        #endregion

        private Tuple<int, int> CalcYinHuanNum(PlaceResidentFireInput request)
        {
            var numyhwtXf = 0;
            if (request.UseElectricBicycle)
            {
                numyhwtXf += 1;
            }

            if (request.UseBottledLiquefiedGas)
            {
                numyhwtXf += 1;
            }

            if (request.UseStackedItems)
            {
                numyhwtXf += 1;
            }

            if (request.UseBurglarMesh)
            {
                numyhwtXf += 1;
            }

            if (request.UseCeiling)
            {
                numyhwtXf += 1;
            }

            if (request.IsCompletelyIsolated)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableMaterials)
            {
                numyhwtXf += 1;
            }

            if (request.UnauthorizedElectricalConnect)
            {
                numyhwtXf += 1;
            }

            if (request.ChargingFacilitiesNoStandard)
            {
                numyhwtXf += 1;
            }

            if (request.NotEnoughExits)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableInsulationMaterials)
            {
                numyhwtXf += 1;
            }

            if (request.UseFlammableDangerousGoods)
            {
                numyhwtXf += 1;
            }

            if (!request.AboveThreeFloorSelf)
            {
                numyhwtXf += 1;
            }

            //if (!request.UseIndependentSmokeAlarm)
            //{
            //    numyhwtXf += 1;
            //}

            //if (!request.AboveThreeFloorsEscape)
            //{
            //    numyhwtXf += 1;
            //}

            var level = 2;
            if (numyhwtXf == 0)
            {
                level = 2;
            }
            else if (numyhwtXf >= 1 && numyhwtXf < 4)
            {
                level = 3;
            }
            else if (numyhwtXf >= 4)
            {
                level = 1;
            }

            return new Tuple<int, int>(numyhwtXf, level);
        }

        private Tuple<int, int> CalcYinHuanNum(PlaceResidentIntegrationInput request)
        {
            var level0 = false;
            var numyhwtGa = 0;
            if (!string.IsNullOrEmpty(request.Security))
            {
                var jsonObj = JsonConvert.DeserializeObject<ResidentIntegrationSecurity>(request.Security);
                if (jsonObj.List != null)
                {
                    foreach (var item in jsonObj.List)
                    {
                        if (item.Checked)
                        {
                            numyhwtGa += 1;
                        }

                        if ("现存违法犯罪窝点".Equals(item.Title) || "违法滋事风险人员居住".Equals(item.Title))
                        {
                            level0 = item.Checked;
                        }
                    }
                }
            }

            var level = 2;
            if (level0)
            {
                level = 1;
            }
            else
            {
                if (numyhwtGa == 0)
                {
                    level = 2;
                }
                else if (numyhwtGa == 1)
                {
                    level = 3;
                }
                else if (numyhwtGa > 1)
                {
                    level = 1;
                }
            }

            return new Tuple<int, int>(numyhwtGa, level);
        }
    }
}
